package com.umfwechat.lightprogram.interceptor;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.umfwechat.common.constant.CacheConsts;
import com.umfwechat.common.constant.CommonConsts;
import com.umfwechat.util.RedisUtil;
import com.umfwechat.util.StringUtil;

public class PermConfInterceptor {
	private static final Logger logger = LoggerFactory.getLogger(PermConfInterceptor.class);
	JSONObject jsonObject = new JSONObject();
	
	public boolean permConf(String data)throws UnsupportedEncodingException{
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		ServletRequestAttributes sra = (ServletRequestAttributes) ra;
		HttpServletRequest request = sra.getRequest();
		JSONObject param=JSONObject.fromObject(data);
		logger.info("请求的入参："+param.toString());
		String tokenId = param.optString("loginToken");	//用户凭证
		if(tokenId !=null && !"".equals(tokenId)){
			String userId = param.optString("loginUserId");	//用户
			if(!"admin".equals(userId)){
				String agentId = param.optString("loginAgentId");	//用户
				String strDow;
				try {
					strDow = RedisUtil.get(CacheConsts.ISFORBIDDEN+agentId+userId);
				} catch (Exception e1) {
					logger.info("redis服务器异常：",e1);
					return true;
				}
				if(StringUtil.isNotEmpty(strDow)){
					jsonObject.put("retCode", "00434113");
					jsonObject.put("retMsg", "该业务员已被admin停用，请联系管理员");
					param = JSONObject.fromObject(jsonObject);
					return true;
				}
				String confStr;
				try {
					confStr = RedisUtil.get(CacheConsts.PERMISSIONCONF+agentId+userId);
				} catch (Exception e) {
					logger.info("redis服务器异常：",e);
					return true;
				}
				String paramVal = param.optString("loginPermConf");//获取登录中权限配置的公共参数
				int num1 = -1;
				int num2 = -1;
				int num3 = -1;
				int num4 = -1;
				int num5 = -1;
				int num6 = -1;
				//searchStorePerm	fetchBillDocPerm	searchProfitPerm
				if(paramVal.contains("searchStorePerm")){
					num1 = 0;
				}
				if(paramVal.contains("fetchBillDocPerm")){
					num2 = 0;
				}
				if(paramVal.contains("searchProfitPerm")){
					num3 = 0;
				}
				if(confStr.contains("searchStorePerm")){
					num4 = 0;
				}
				if(confStr.contains("fetchBillDocPerm")){
					num5 = 0;
				}
				if(confStr.contains("searchProfitPerm")){
					num6 = 0;
				}
				
				if(num1 == num4 && num2 == num5 && num3 == num6){
					return false;
				}else{
					jsonObject.put("retCode", "00434114");
					jsonObject.put("retMsg", "该业务员权限被已被admin关闭，请联系管理员");
					param = JSONObject.fromObject(jsonObject);
					return true;
				}
			}
		}
		return false;
	}
	
	public JSONObject result() {
		return jsonObject;
	}
}
